/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.servlet;

import com.util.SQLConnection;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import javax.annotation.Resource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 *
 * @author chetans
 */
public class ExportServlet extends HttpServlet {

    private Logger myLogger = Logger.getLogger("RootLogger");

    private int getNumberOfDays(String dateRange){
        myLogger.info("Entering with date range :"+dateRange);
        int numOfDays=0;
        String[] dates =dateRange.split("-");
        int startDate = Integer.parseInt(dates[0]);
        int endDate = Integer.parseInt(dates[1]);
        numOfDays = (endDate-startDate)+1;
        myLogger.info("Number of days in current Week :"+numOfDays);
        myLogger.info("Exiting..");
        return numOfDays;
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        myLogger.info("Entering..");
        String month =(String) request.getParameter("month");
        String year = (String) request.getParameter("year");
        int imon = Integer.parseInt(month);
        int iyear = Integer.parseInt(year);
        myLogger.info("year :"+iyear+" month :"+imon);
        StringBuilder exportData=new StringBuilder();
        String currentWeek;
        int firstDayOfTheWeek;
        int numOfDaysInWeek;
        boolean noDataToExport = true;
        try{
            PrintWriter out = response.getWriter();
            response.setContentType("text/xml");
            response.addHeader("Content-Disposition","attachment;filename=\"exportData.xml\"");

            PreparedStatement pstmt;
            ResultSet rs;
            Connection con;
            con = new SQLConnection().getMySQLConnection();
            pstmt = con.prepareStatement("select * from task_records where month =? and year=? order by week");
            pstmt.setInt(1, imon);
            pstmt.setInt(2, iyear);
            rs=pstmt.executeQuery();
            String lastWeek="";
            boolean isWeekEndTagPrinted = true;
            exportData.append("<export-data>\n");
            exportData.append("<year>"+iyear+"</year>\n");
            exportData.append("<month>"+imon+"</month>\n");
            while(rs.next()){
                noDataToExport=false;
                currentWeek=rs.getString("week");
                myLogger.info("Current week is :"+currentWeek);
				if(lastWeek.equals("")){
					//First week of the month or in case only one previous record
					myLogger.debug("Adding week first time..");
					exportData.append("\t<week>\n");
                    exportData.append("\t<date-range>"+currentWeek+"</date-range>\n");
				}else if(lastWeek.equals(currentWeek)){
                    //do not append week
					myLogger.debug("Same week as the last week..");
                    isWeekEndTagPrinted = false;
                }else{
                    //append end tag
                     myLogger.debug("Adding end tag..");
					 exportData.append("\t</week>\n");
                     exportData.append("\t<week>\n");
                     exportData.append("\t<date-range>"+currentWeek+"</date-range>\n");
					 isWeekEndTagPrinted = false;
                }
                    
                    exportData.append("\t\t<task>\n");
                    exportData.append("\t\t<name>"+rs.getString("task_name")+"</name>\n");
                    firstDayOfTheWeek= Integer.parseInt(currentWeek.substring(0, rs.getString("week").indexOf("-")));
                    //lastDayOfTheWeek = Integer.parseInt(currentWeek.substring(rs.getString("week").indexOf("-")+1,currentWeek.length()-1));
                    numOfDaysInWeek = getNumberOfDays(currentWeek);
                    for(int i=1;i<=numOfDaysInWeek;i++){
                        exportData.append("\t\t<day>\n");
                        exportData.append("\t\t\t<date>"+firstDayOfTheWeek+"/"+imon+"/"+iyear+"</date>\n");
                        exportData.append("\t\t\t<num-of-hrs>"+rs.getString("day"+i)+"</num-of-hrs>\n");
                        exportData.append("\t\t</day>\n");
                        firstDayOfTheWeek++;
                    }
                exportData.append("\t\t</task>\n");
                lastWeek=currentWeek;
            }
            if (!isWeekEndTagPrinted){
                exportData.append("\t</week>\n");//IF there's a single task record
				myLogger.debug("Adding end tag outside while..");
			}
            if(noDataToExport){
                exportData.append("No data to export\n");
                myLogger.warn("No data to export");
            }
                
            exportData.append("</export-data>\n");
            myLogger.info("Export XML constructed is :"+exportData.toString());
            out.print(exportData.toString());
            myLogger.info("Exiting..");
        }catch(SQLException SQLE) {
            SQLE.printStackTrace();
            myLogger.error("SQLException :"+SQLE);
        }catch(NullPointerException NPE){
            NPE.printStackTrace();
            myLogger.error("NullPointerException :"+NPE);
        }catch(Exception e){
            e.printStackTrace();
            myLogger.error("Exception :"+e);
        }
    } 
}
